/**
 * @file HexProcess.c
 * @brief 
 * @author xuesong (wenshaoliu@foxmail.com)
 * @version 1.0
 * @date 2024-11-06
 * 
 * @copyright Copyright (c) 2024  by xuesong
 * 
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version <th>Author  <th>Description
 * <tr><td>2024-11-06     <td>1.0     <td>xuesong   <td>内容
 * </table>
 */
#include "HexProcess.h"

uint32_t Hex2Dec(uint32_t data)
{
    uint32_t tempData = 0;
    uint8_t index = 0, i = 0;
    uint8_t *pData = NULL;

    do
    {
        pData = (uint8_t *)&data;
        pData += 3;

        tempData <<= 1;
        if (*pData & 0x80)
        {
            tempData |= 0x01;
        }
        data <<= 1;
        index++;
        if (index >= 32)
            break;
        pData = (uint8_t *)&tempData;
        for (i = 0; i < 4; i++)
        {
            if ((*pData + 0x03) & 0x08)
                *pData += 3;
            if ((*pData + 0x30) & 0x80)
                *pData += 0x30;
            pData++;
        }
    } while (index < 32);

    return tempData;
}

/**
 * @brief F_RRL_Buff_Nbits
 *                  ;缓存默认采用小端模式,实际应用需注意
 * @param buffer    ;等待移位的缓存
 * @param len       ;缓存长度
 * @param Nbits      ;移位长度
 * @param deration  ;移位方向 0:<<   1:>>
 */
void F_RRL_Buff_Nbits(uint8_t *buffer, uint8_t len, uint8_t Nbits, uint8_t deration)
{
    uint8_t *startPoint = NULL;
    uint8_t bitCnt = 0, byteCnt = 0;
    uint8_t backUpByteData = 0;
    uint8_t crossBit = 0;
    uint8_t derationBit = 0x01; //<左移 从低字节开始移,高位被移出,转移到高字节最低位
    uint8_t outBit = 0x80;      //>
    if (deration)               //<右移 从高字节开始移,低位被移出,转移到低字节最高位
    {
        outBit = 0x01;
        derationBit = 0x80;
    } //>
    if (buffer != NULL)
    {
        for (bitCnt = 0; bitCnt < Nbits; bitCnt++)
        {
            startPoint = buffer; // 默认左移,从低字节开始
            if (deration)
                startPoint += (len - 1); // 右移从高字节开始

            crossBit = 0;
            for (byteCnt = 0; byteCnt < len; byteCnt++)
            {
                backUpByteData = *startPoint;
                if (deration) // 右移
                    *startPoint = (*startPoint) >> 1;
                else // 左移
                    *startPoint = (*startPoint) << 1;
                *startPoint |= crossBit;
                crossBit = 0;
                if (backUpByteData & outBit)
                    crossBit = derationBit;
                if (deration) // 右移
                    startPoint--;
                else // 左移
                    startPoint++;
            }
        }
    }
}